<?php
/**
 * Created by PhpStorm
 * User: Jhinwy
 * Date: 5/29/24
 * Time: 9:44 AM
 */

namespace App\Console\Commands;

use App\Models\WechatCorp;
use App\Services\KfAccountService;
use GuzzleHttp\Client;
use Illuminate\Console\Command;
use App\Models\WechatDepartment as DepModel;
use Illuminate\Support\Facades\Log;


/**
 * 拉取企业微信部门，组织架构
 *
 * Class Push
 * @package App\Console\Commands
 */
class WechatDepartment extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'wechat:department';


    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '拉取企业微信部门';


    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }


    /**
     *
     * @return bool
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function handle()
    {
        $corpIds = WechatCorp::query()->pluck('corp_id')->toArray();
        $client  = new Client();
        $service = new KfAccountService();
        foreach ($corpIds as $corpId) {
            $token    = $service->getReplaceAccessToken($corpId);
            $response = $client->request('GET', sprintf($service->api['dep_list'], $token));
            if ($response->getStatusCode() != 200) {
                continue;
            }
            $contents       = $response->getBody()->getContents();
            Log::info('同步：' . $corpId . '企业部门：' ,[$contents]);

            $data           = json_decode($contents, true);
            $departmentList = $data['department'] ?? [];
            Log::info('同步：' . $corpId . '企业部门，共计：' . count($departmentList) . '条');
            foreach ($departmentList as $item) {
                $dep                  = DepModel::query()->firstOrNew(['corp_id' => $corpId, 'department_id' => $item['id']]);
                $dep->department_name = $item['name'] ?? '';
                $dep->parent_id       = $item['parentid'] ?? 0;
                $dep->order           = $item['order'] ?? 0;
                $dep->save();
            }
        }
        Log::info('同步企业部门完成');
    }

}
